<?php
// 增强错误报告
// error_reporting(E_ALL);
// ini_set('display_errors', '1');
// ini_set('log_errors', '1');
// ini_set('error_log', __DIR__ . '/php_errors.log');

// 设置自定义异常处理
// set_exception_handler(function ($exception) {
//     error_log("未捕获异常: " . $exception->getMessage());
//     header('Content-Type: application/json');
//     http_response_code(500);
//     echo json_encode([
//         'error' => 'Internal Server Error',
//         'message' => $exception->getMessage(),
//         'file' => $exception->getFile(),
//         'line' => $exception->getLine(),
//         'trace' => $exception->getTrace()
//     ]);
//     exit;
// });

error_log("app start ar - " . date('Y-m-d H:i:s'));
require_once __DIR__ . '/../vendor/autoload.php';

// use Slim\App;
// use DI\Container;
// use Slim\Factory\AppFactory;
use DI\Bridge\Slim\Bridge as SlimBridge;
use DI\ContainerBuilder;
use Psr\Container\ContainerInterface;
use Slim\Routing\RouteCollectorProxy;
use Src\middleware\AuthMiddleware;
use Src\middleware\AdminMiddleware;
use Src\config\Db;
use Src\controller\BlogController;
use Src\controller\AuthController;
use Src\controller\UserController;
use Slim\Factory\ServerRequestCreatorFactory;
use Src\middleware\JsonParsingErrorMiddleware;
use Src\middleware\SessionMiddleware;
use Src\controller\AdminController;

define("ROOT_PATH", __DIR__ . "/../src");

// 数据库配置
/**
 * @var array $dbConfig
 */
$dbconfig = require ROOT_PATH . '/config/Dbconfig.php';
// $db = new Db($dbconfig);

// $container = new Container();
// AppFactory::setContainer($container);
// 初始化Slim应用
// $app = AppFactory::create();
$containerBuilder = new ContainerBuilder();
$containerBuilder->useAutowiring(true);
$containerBuilder->useAnnotations(true);
// 注册控制器
$containerBuilder->addDefinitions([
    'config' => [
        'db' => $dbconfig
    ],
    'db' => function (ContainerInterface $c) use ($dbconfig) {
        return new Db($dbconfig);
    },
    "BlogController" => function (ContainerInterface $c) {
        return new BlogController($c->get('db'));
    },
    "AuthController" => function (ContainerInterface $c) {
        return new AuthController($c->get('db'));
    },
    "UserController" => function (ContainerInterface $c) {
        return new UserController($c->get('db'));
    },
    "AdminController" => function (ContainerInterface $c) {
        return new AdminController($c->get('db'));
    },
]);
$container = $containerBuilder->build();
$app = SlimBridge::create($container);

// 获取容器
// $container = $app->getContainer();




// CORS中间件
$app->options('/{routes:.+}', function ($request, $response, $args) {
    return $response;
});

$app->add(function ($request, $handler) {
    $response = $handler->handle($request);
    return $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
});
$app->addBodyParsingMiddleware();
$app->add(new JsonParsingErrorMiddleware());
// 公共路由
$app->group('', function (RouteCollectorProxy $group) {
    error_log("register all routes ");

    // 认证路由
    $group->post('/auth/register', 'AuthController:register');
    $group->post('/auth/login', 'AuthController:login');
    $group->get('/auth/logout', 'AuthController:logout');

    // 博客路由
    $group->get('/blogs', 'BlogController:getBlogs');
    $group->get('/blog/{id}', 'BlogController:getBlog');
});

// 需要认证的路由
$app->group(
    '',
    function (RouteCollectorProxy $group) use ($app) {
        // 密码修改
        $group->put('/auth/change-password', 'AuthController:changePassword');

        // 用户路由
        $group->put('/user/{user_id}', 'UserController:updateUser');
        $group->get('/user/{user_id}', 'UserController:getUser');

        // 博客路由
        $group->post('/blog', 'BlogController:createBlog');
        $group->put('/blog/{id}', 'BlogController:updateBlog');
        $group->delete('/blog/{id}', 'BlogController:deleteBlog');
        $group->get('/user/{user_id}/blogs', 'BlogController:getUserBlogs');
        $group->get('/admin/stats', 'AdminController:stats');

        // 管理员路由
        $group->group('', function ($group) {
            $group->get('/allusers', 'UserController:getAllUsers');
            $group->get('/users', 'UserController:getUsersPage');
            $group->delete('/user/{user_id}', 'UserController:deleteUser');
            $group->put('/user/{user_id}/reset-password', 'AuthController:resetPassword');
            $group->get('/allblogs', 'BlogController:getAllBlogs');
        })->add(new AdminMiddleware($app->getResponseFactory()));
    }
)->add(new AuthMiddleware($app->getResponseFactory()));

$app->add(new SessionMiddleware());

use Src\errorhandler\HttpErrorHandler;
use Src\errorhandler\ShutdownHandler;
// global error handler
$displayErrorDetails = true;
$callableResolver = $app->getCallableResolver();
$responseFactory = $app->getResponseFactory();
$serverRequestCreator = ServerRequestCreatorFactory::create();
$request = $serverRequestCreator->createServerRequestFromGlobals();
$errorHandler = new HttpErrorHandler(callableResolver: $callableResolver, responseFactory: $responseFactory);
$shutdownHandler = new ShutdownHandler(request: $request, errorHandler: $errorHandler, displayErrorDetails: $displayErrorDetails);
register_shutdown_function(callback: $shutdownHandler);


$errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, false, false);
$errorMiddleware->setDefaultErrorHandler($errorHandler);

// 运行应用
error_log("app runing!");
$app->run();


?>